import { useState, useCallback, useEffect } from "react";
import { View, Text, ScrollView, Pressable } from "react-native";

import Btn from "@/components/Btn";
import globalMethods from "@/GlobalMethodProvider";

import type { RootState } from "@/store";
import { useSelector } from "react-redux";
import { getPlan } from "@/api/videoDisplay";

import sm from "@/utils/ScheduleManage/operate";
import fso from "@/utils/FileOperate/operate";

import config from "@/config";
import { scheduleSqlh, materialSqlh } from "@/sqlite/exports";
import type { ScheduleSqliteType, MaterialSqliteType } from "@/sqlite/exports";

import styles from "./styles";
import staticSchedule from "@/staticSchedule/staticSchedule";
import useViewList from "@/hooks/useViewList";
import theme from "@/styles/theme";
import SchduleInfoCard from "@/components/SchduleInfoCard";

/** 页面状态类型 */
type StateType = {
  /** 本地所有的排期数据 */
  allSchedule: ScheduleSqliteType[];
  /** 当前查看的排期 */
  curSchedule: ScheduleSqliteType | null;
  /** 排期关联的素材数据 */
  linkMaterial: MaterialSqliteType[];
};

/** 排期信息 */
const ScheduleInfo = () => {
  const [state, _setState] = useState<StateType>({
    allSchedule: [],
    curSchedule: null,
    linkMaterial: []
  });

  // 通用更新状态单个
  const setState = useCallback((field: keyof typeof state, val: any) => {
    _setState(_state => {
      return { ..._state, [field]: val };
    });
  }, []);

  // 通用更新状态(对象)
  const setObjState = useCallback((obj: Partial<typeof state>) => {
    _setState(_state => {
      return { ..._state, ...obj };
    });
  }, []);

  const { index: reduxIndex } = useSelector((state: RootState) => state);

  const curSchedule = reduxIndex.curSchedule;

  /** 统计扫描到的资产信息 */
  const {
    open: openViewList,
    close: closeViewList,
    Comp: CompViewList
  } = useViewList({
    showDel: false,
    modalBoxProps: {
      title: "素材信息",
      width: "80%",
      dismissable: false,
      hideCloseBtn: true,
      onConfirm() {
        closeViewList();
      }
    },
    ComtentBefore() {
      return (
        <View>
          <Text style={styles.linkMaterialTip}>
            {state.curSchedule?.name} 关联素材数据 {state.linkMaterial.length}条, 具体素材信息如下:
          </Text>
        </View>
      );
    },
    getShowItemField() {
      return [
        {
          label: "排序",
          value: (item: MaterialSqliteType) => item.sort
        },
        {
          label: "名称",
          value: (item: MaterialSqliteType) => item.name
        },
        {
          label: "开始时间",
          value: (item: MaterialSqliteType) => item.startTime
        },
        {
          label: "结束时间",
          value: (item: MaterialSqliteType) => item.endTime
        },
        {
          label: "时长",
          value: (item: MaterialSqliteType) => item.duration
        },
        {
          label: "分辨率",
          value: (item: MaterialSqliteType) => item.resolution
        },
        {
          label: "是否下载",
          value: (item: MaterialSqliteType) => {
            return (
              <Text style={{ color: item.isDown === "1" ? theme.danger : theme.primary, fontWeight: "bold" }}>
                {item.isDown === "2" ? "是" : "否"}
              </Text>
            );
          }
        },
        {
          label: "大小",
          value: (item: MaterialSqliteType) => item.size
        }
      ];
    }
  });

  /** 初始化 */
  const getInitData = useCallback(async () => {
    try {
      if (scheduleSqlh) {
        const list = await scheduleSqlh.getList<ScheduleSqliteType[]>();
        setState("allSchedule", list);
      } else {
        globalMethods.$error("排期数据库初始化失败");
      }
    } catch (err) {
      console.log("err: ", err);
      globalMethods.$error("发生了错误: " + err);
    }
  }, [setState]);


  useEffect(() => {
    getInitData();
  }, [getInitData]);

  const DevComp = config.IS_DEBUG && (
    <ScrollView horizontal>
      <View style={{ flex: 1, flexDirection: "row", gap: 10 }}>
        <Btn
          text="同步排期"
          type="primary"
          onClick={async () => {
            try {
              const res = await getPlan(reduxIndex.entryNetworkInfo?.code || "");
              console.log("排期数据: ", res);
              globalMethods.$showLoading("获取排期数据中");
              // 同步排期
              const flag = await sm.syncSchedule();
              if (!flag) {
                // 这里要重试
                globalMethods.$error("排期数据同步失败");
                return;
              }
              getInitData();
            } catch (err) {
              console.log("err: ", err);
            } finally {
              globalMethods.$hideLoading();
            }
          }}
        />
        <Btn
          type="primary"
          text="定时查找排期"
          onClick={() => {
            sm.loopSeek();
          }}
        />
        <Btn
          type="primary"
          text="停止定时查找排期"
          onClick={() => {
            sm.stopSeek();
          }}
        />
        <Btn
          type="danger"
          text="清空排期和素材"
          onClick={() => {
            scheduleSqlh?.clearTable();
            materialSqlh?.clearTable();
          }}
        />
      </View>
    </ScrollView>
  );

  const EmptyComp = <Text>本地暂无排期数据</Text>;

  const AllScheduleComp = state.allSchedule.map((schedule, i) => {
    return (
      <View style={styles.item} key={i}>
        {curSchedule[0]?.sourceId === schedule.sourceId && <Text style={styles.curTip}>当前播放</Text>}

        <View style={styles.card}>
          <View style={styles.label}>
            <View style={styles.indexContainer}>
              <Text style={styles.index}>{i + 1}</Text>
            </View>
            <Text style={styles.text}>{schedule.startDate?.split(" ")?.[0] || "未设置开始时间"}</Text>
            <Text style={styles.text}>至</Text>
            <Text style={styles.text}>{schedule.endDate?.split(" ")?.[0] || "未设置结束时间"}</Text>
          </View>

          <SchduleInfoCard schedule={schedule} />
        </View>
      </View>
    );
  });

  const ScheduleListComp = (
    <ScrollView style={styles.container}>
      <Pressable>
        {DevComp}

        {state.allSchedule.length > 0 ? AllScheduleComp : EmptyComp}
      </Pressable>

      {CompViewList}
    </ScrollView>
  );

  return ScheduleListComp;
};

export default ScheduleInfo;
